﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace Sharp.Platform.Mvc
{
    public class CustomIdentity : IIdentity
    {
        private FormsAuthenticationTicket ticket;
        private HttpContext context = HttpContext.Current;

        public CustomIdentity(FormsAuthenticationTicket ticket)
        {
            this.ticket = ticket;
        }

        public string AuthenticationType
        {
            get { return "Custom"; }
        }

        public bool IsAuthenticated
        {
            get { return true; }
        }

        public string Name
        {
            get
            {
                return ticket.Name;
            }
        }

        public FormsAuthenticationTicket Ticket
        {
            get { return ticket; }
        }

        // 这里可以是任意来自数据库的值，由Name属性取得
        // 需要注意此时已通过身份验证
        public string Email
        {
            get
            {
                HttpCookie cookie = context.Request.Cookies["Email"];

                if (cookie == null || String.IsNullOrEmpty(cookie.Value))
                {
                    string type = "jimmy_dev[at]163.com";   // 实际应根据name属性从数据库中获得
                    cookie = new HttpCookie("UserType", type);
                    cookie.Expires = DateTime.Now.AddDays(1);
                    context.Response.Cookies.Add(cookie);
                }

                return cookie.Value;
            }
        }

        public string HomePage
        {
            get
            {
                HttpCookie cookie = context.Request.Cookies["HomePage"];

                if (cookie == null || String.IsNullOrEmpty(cookie.Value))
                {
                    string name = "www.tracefact.net";      // 实际应根据name属性从数据库中获得
                    cookie = new HttpCookie("NickName", name);
                    cookie.Expires = DateTime.Now.AddDays(1);
                    context.Response.Cookies.Add(cookie);
                }
                return cookie.Value;
            }
        }
    }
}
